import React, { useState, Key, useEffect } from "react";
import {
  Button,
  Tree,
  Card,
  message,
  Row,
  Col,
  Tag,
  Pagination,
  Table,
} from "antd";
import { useNavigate } from "react-router";
import { useParams } from "react-router-dom";
import type { DataNode, DirectoryTreeProps } from "antd/es/tree";
import type { PaginationProps } from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  reqGetDepList,
  reqGetSchedulDetailList,
  reqGetSchedulRuleList,
} from "@/api/hospital/hospitalList/index";
import type {
  DepList,
  SchedulDetailList,
  BookingScheduleList,
  SchedulDetailItem,
} from "@/api/hospital/hospitalList/model/hospitalListTypes";

// const { DirectoryTree } = Tree;
// const treeData: DataNode[] = [
//   {
//     title: "parent 0",
//     key: "0-0",
//     children: [
//       { title: "leaf 0-0", key: "0-0-0", isLeaf: true },
//       { title: "leaf 0-1", key: "0-0-1", isLeaf: true },
//     ],
//   },
//   {
//     title: "parent 1",
//     key: "0-1",
//     children: [
//       { title: "leaf 1-0", key: "0-1-0", isLeaf: true },
//       { title: "leaf 1-1", key: "0-1-1", isLeaf: true },
//     ],
//   },
// ];

// 全局变量
let depcode: string;
// 组件函数
const HospitalSchedul = () => {
  const navigate = useNavigate();
  const params = useParams();
  const { hoscode } = params;

  // 科室数据
  const [dep, setDep] = useState<DepList>([]);
  const [depcodes, setDepcodes] = useState<string[]>([]);

  // 排班详情列表数据
  const [schedulDetailList, setSchedulDetailList] = useState<SchedulDetailList>(
    []
  );
  // 排班规则数据
  const [schedulRuleList, setSchedulRuleList] = useState<BookingScheduleList>(
    []
  );
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);

  // 导航数据
  const [hosname, setHosname] = useState("");
  const [depname, setDepname] = useState("");
  const [wordDate, setWordDate] = useState("");

  // 获取科室回调
  const getDepList = async () => {};
  // 获取workDate排班日期的排班详细列表
  const getSchedulDetailList = async (wordDate: string) => {
    const res = await reqGetSchedulDetailList(
      hoscode as string,
      depcode,
      wordDate
    );
    console.log(res);
    setSchedulDetailList(res);
  };
  // 获取排班规则数据
  const getSchedulRuleList = async (
    page: number,
    pageSize: number,
    depcode: string
  ) => {
    if (hoscode) {
      const res = await reqGetSchedulRuleList({
        page,
        limit: pageSize,
        hoscode,
        depcode,
      });
      // console.log(res);
      setSchedulRuleList(res.bookingScheduleList);
      setTotal(res.total);
      setHosname(res.baseMap.hosname);
      setWordDate(res.bookingScheduleList[0]?.workDate);
      // 把排班日期返回
      return res.bookingScheduleList[0]?.workDate as string | false;
    }
  };

  useEffect(() => {
    const fetch = async () => {
      // 返回当前匹配路由的路由参数
      // const {hoscode} = useParams()
      const res = await reqGetDepList(hoscode as string);
      console.log(res);
      setDep(res);
      // 得到key[]
      setDepcodes(
        res.map((item) => {
          return item.depcode;
        })
      );

      // 设置默认的门诊名称
      setDepname(res[0]?.children[0]?.depname);

      // 设置全局的科室编码
      depcode = res[0]?.children[0]?.depcode;
      console.log(depcode);

      const wordDate = await getSchedulRuleList(page, pageSize, depcode);
      console.log(wordDate);

      getSchedulDetailList(wordDate as string);
    };
    fetch();
  }, []);

  // 点击树节点触发
  const onSelect: DirectoryTreeProps["onSelect"] = async (keys, info) => {
    // console.log("Trigger Select", keys, info);
    // const depcode = (info as any).node.depcode;
    depcode = keys[0] as string; //修改全局的depcode
    // 记得await
    const wordDate = await getSchedulRuleList(1, pageSize, depcode);
    if (!wordDate) {
      message.warning("暂无数据");
      setSchedulDetailList([]);
      return;
    }
    getSchedulDetailList(wordDate as string);
  };

  // 行
  const columns: ColumnsType<SchedulDetailItem> = [
    {
      title: "序号",
      dataIndex: "name",
      render(text, recode, index) {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号院时间",
      dataIndex: "workDate",
    },
    {
      title: "可预约数",
      dataIndex: "availableNumber",
    },
    {
      title: "剩余预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "挂号费（元）",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];

  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {wordDate}
      </p>

      <Row>
        <Col span={5}>
          <div
            style={{
              border: "1px #ccc solid",
              marginRight: 20,
              height: 300,
              overflow: "scroll", //超出300 滚动
            }}
          >
            {/* 
              defaultExpandAll  默认展开所有树节点
              fieldNames 自定义节点 title、key、children 的字段
              height 设置虚拟滚动容器高度
              multiple 支持点击多个节点
              onExpand 展开/收起节点时触发
              onSelect 点击树节点触发
            */}
            <Tree
              expandedKeys={depcodes} //默认展开的key
              onSelect={onSelect}
              treeData={dep as any}
              fieldNames={{
                title: "depname",
                key: "depcode",
              }}
            />
          </div>
        </Col>
        <Col span={19}>
          <div style={{ marginBottom: 20 }}>
            {schedulRuleList.map((item, index) => {
              return (
                <Tag
                  color={wordDate === item.workDate ? "green" : ""}
                  style={{ width: 102, height: 44 }}
                  key={index}
                  onClick={async () => {
                    // 注意setWordDate要获取最新数据，写函数形式，第二个参数
                    setWordDate(item.workDate);
                    // console.log(wordDate);
                    // console.log(item.workDate);                   
                    getSchedulDetailList(item.workDate);
                  }}
                >
                  {item.workDate} {item.dayOfWeek}
                  <br />
                  {item.availableNumber} / {item.reservedNumber}
                </Tag>
              );
            })}
          </div>
          <Pagination
            showSizeChanger
            total={total}
            current={page} //控制分页器高亮页码
            pageSize={pageSize} //每页条数
            pageSizeOptions={[2, 5, 10]}
            onChange={async (page, pageSize) => {
              setPage(page);
              setPageSize(pageSize);
              console.log(page, pageSize, depcode);

              const wordDate = await getSchedulRuleList(
                page,
                pageSize,
                depcode
              );
              console.log(wordDate);

              getSchedulDetailList(wordDate as string);
            }}
          />
          {/* 
            去掉table默认的分页器
          */}
          <Table
            dataSource={schedulDetailList}
            columns={columns}
            pagination={false}
            style={{ marginTop: 20, marginBottom: 20 }}
            bordered
            rowKey={"id"}
          />
          <Button
            onClick={() => {
              navigate(-1);
            }}
          >
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  );
};

export default HospitalSchedul;
